import { DictArray } from "../utils/array.util"

export default class SimplePostMessage {
  sourceId: string
  targetId: string
  target: any
  messageHandlers: any
  onMessage: (t: any) => void
  constructor(t, e, s) {
    this.sourceId = t
    this.targetId = e
    this.target = s
    this.messageHandlers = new DictArray()
    this.onMessage = t => {
      const { type: e, fromId: s, toId: i } = t.data
      if (s !== this.targetId || i !== this.sourceId) return
      const r = this.messageHandlers.getValuesAtKey(e)
      for (const e of r) e(...t.data.payload)
    }
    window.addEventListener("message", this.onMessage)
  }
  updateTarget(t) {
    this.target = t
  }
  facade() {
    const t = this
    return new (class PostMessageFacade {
      dispose() {
        t.dispose()
      }
      on(e, s) {
        t.on(e, s)
      }
      off(e, s) {
        t.off(e, s)
      }
      send(e, ...s) {
        t.send(e, ...s)
      }
    })()
  }
  dispose() {
    window.removeEventListener("message", this.onMessage), (this.messageHandlers = new DictArray())
  }
  on(t, e) {
    this.messageHandlers.add(t, e)
  }
  off(t, e) {
    this.messageHandlers.remove(t, e)
  }
  send(t, ...e) {
    this.target.postMessage({ toId: this.targetId, fromId: this.sourceId, type: t, payload: e }, "*")
  }
}
